﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

using System.Windows.Data;
using System.Xml;
using System.Xml.Linq;
using ObjModel = System.Collections.ObjectModel;

namespace OrgStructure
{

    public partial class Welcome : Page
    {

        #region Members

        private Double _y = 0;

        #endregion

        #region Constructor
        public Welcome()
        {
            InitializeComponent();
            dataGrid1.ItemsSource = App._SPUSersList_Active;
            App._timer.Tick += new EventHandler(myTimer_Tick);
            App._timer.Interval = new TimeSpan(0, 0, 0, 0, 90);
        }
        #endregion

        #region Events
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            StartInvalidateTree();
        }
        private void myTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            Topic oldValue = e.OldValue as Topic;
            Topic newValue = e.NewValue as Topic;
            App.CurSelNode = newValue;
            dataGrid1.ItemsSource = null;
            App._SPUSersList_Active.Clear();
            App._SPUSersList_Active = null;
            App._SPUSersList_Active = new List<SPUser>();
            StartSplash();

            if (App._SPUSersList.Count <= 0)
                return;
            if (App.CurSelNode == null)
                return;

            DeparmentName.Text = "Отдел : " + App.CurSelNode.Title;

            string department = App.CurSelNode.Title;
            List<string> DepList = new List<string>();
            DepList.Add(department);
            CatDepParentNames(App.CurSelNode, ref DepList);

            foreach (SPUser u in App._SPUSersList)
            {
                if (DepFind(ref DepList, u.Отдел))
                    App._SPUSersList_Active.Add(u);
            }

            dataGrid1.SelectionMode = DataGridSelectionMode.Single;
            dataGrid1.ItemsSource = App._SPUSersList_Active;
            if (App._SPUSersList_Active.Count > 0)
            {
                dataGrid1.SelectedIndex = 0;
            }
                
        }
        void CatDepParentNames(Topic Parent, ref List<string> s)
        {
            if (Parent.Title == "Можайское")
                return;
            foreach (Topic t in Parent.ChildTopics)
            {
                CatDepParentNames(t, ref s);
                s.Add(t.Title);
            }
        }
        bool DepFind(ref List<string> list, string str)
        {
            foreach (string s in list)
            {
                if (s == str)
                    return true;
            }
            return false;
        }
        #endregion

        #region Data
        void StartInvalidateTree()
        {
            App._IsLoading = true;

            App._mainpage.hyperlink_all.IsEnabled = false;
            App._mainpage.hyperlink_office.IsEnabled = false;
            App._mainpage.hyperlink_search.IsEnabled = false;
            App._mainpage.hyperlink_shops.IsEnabled = false;

            StartSplash();
            myTreeView.DataContext = null;
            App._list.Clear();
            App._list = null;
            App._list = new List<MyNode>();
            App.Topics.Clear();
            App.Topics = null;
            App.Topics = new ObjModel::ObservableCollection<Topic>();
            App._SPUSersList.Clear();
            App._SPUSersList = null;
            App._SPUSersList = new List<SPUser>();
            Guid guid = Guid.NewGuid();
            DateTime dt = DateTime.Now;
            WebClient wbcl = new WebClient();
            wbcl.DownloadStringCompleted += new DownloadStringCompletedEventHandler(load_data);
            Uri myUri = new Uri("http://sp.korablik.local:98/ws/Catalog/OneC/OrgStructureXml.aspx?id=" + guid.ToString() + "&date=" + dt.ToShortDateString(), UriKind.Absolute);
            wbcl.DownloadStringAsync(myUri);
            GetSPUsersList();
        }
        void GetSPUsersList()
        {
            Guid guid = Guid.NewGuid();
            DateTime dt = DateTime.Now;
            App._SPUSersList.Clear();
            App._SPUSersList = null;
            App._SPUSersList = new List<SPUser>();
            WebClient wbcl = new WebClient();
            wbcl.DownloadStringCompleted += new DownloadStringCompletedEventHandler(load_data2);
            Uri myUri = new Uri("http://sp.korablik.local:98/ws/Catalog/SPUsers.aspx?id=" + guid.ToString() + "&date=" + dt.ToShortDateString(), UriKind.Absolute);
            wbcl.DownloadStringAsync(myUri);
        }
        void StartSplash()
        {
            _y = 0;
            SplashScreenInvalidate.Visibility = System.Windows.Visibility.Visible;
            myTreeView.IsEnabled = false;
            App._mainpage.hyperlink_all.IsEnabled = false;
            App._mainpage.hyperlink_office.IsEnabled = false;
            App._mainpage.hyperlink_search.IsEnabled = false;
            App._mainpage.hyperlink_shops.IsEnabled = false;
            App._timer.Start();
        }
        void StopSplash()
        {
            if (App._IsLoading == false)
            {
                App._timer.Stop();
                if (App._SPUSersList != null && App._SPUSersList.Count > 0)
                {
                    myTreeView.IsEnabled = true;
                    App._mainpage.hyperlink_all.IsEnabled = true;
                    App._mainpage.hyperlink_office.IsEnabled = true;
                    App._mainpage.hyperlink_search.IsEnabled = true;
                    App._mainpage.hyperlink_shops.IsEnabled = true;
                }
                SplashScreenInvalidate.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        void myTimer_Tick(object sender, EventArgs e)
        {
            _y+=23;
            if (_y > 360)
                _y = 0;
            PanelRight.Projection.SetValue(PlaneProjection.RotationYProperty, _y);
            if (_y == 0)
                StopSplash();
        }
        void load_data(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                App._mainpage.hyperlink_all.IsEnabled = true;
                App._mainpage.hyperlink_office.IsEnabled = true;
                App._mainpage.hyperlink_search.IsEnabled = true;
                App._mainpage.hyperlink_shops.IsEnabled = true;
                App._IsLoading = false;
                MessageBox.Show("Error" + e.Error.Message);                
                return;
            }
            XDocument xDoc = XDocument.Parse(e.Result);
            string strTmp = "";
            var query = from g in xDoc.Descendants("OrgNodes")
                        select new
                        {
                            Val = (string)g.Value.ToString(),
                        };
            foreach (var node in query)
            {
                strTmp = node.Val;
            }
            string[] strSeparator = { "_" };
            string[] nodesStrIDs = strTmp.Split(strSeparator, StringSplitOptions.RemoveEmptyEntries);

            foreach (string s in nodesStrIDs)
            {
                string strTmp2 = "_" + s;
                var query2 = from g2 in xDoc.Descendants(strTmp2)
                             select new
                             {
                                 Val = (string)g2.Value.ToString(),
                                 Elem = (XElement)g2,
                             };
                foreach (var node2 in query2)
                {
                    XElement el = node2.Elem;
                    string Name = "";
                    string idStr = "";
                    string ParentIDStr = "";
                    for (int i = 0; i < el.Attributes().Count(); i++)
                    {
                        XAttribute attr = el.Attributes().ElementAt(i);
                        if (attr.Name == "Name")
                            Name = attr.Value;
                        else if (attr.Name == "ID")
                            idStr = attr.Value;
                        else if (attr.Name == "ParentID")
                            ParentIDStr = attr.Value;
                    }

                    AddData(idStr, ParentIDStr, Name);
                }
            }

            InvalidateTree();

        }
        void load_data2(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                App._mainpage.hyperlink_all.IsEnabled = true;
                App._mainpage.hyperlink_office.IsEnabled = true;
                App._mainpage.hyperlink_search.IsEnabled = true;
                App._mainpage.hyperlink_shops.IsEnabled = true;
                App._IsLoading = false;
                MessageBox.Show("Error" + e.Error.Message);
                return;
            }

            App._SPUSersList.Clear();
            App._SPUSersList = null;
            App._SPUSersList = new List<SPUser>();
            App._SPUSersList_Active.Clear();
            App._SPUSersList_Active = null;
            App._SPUSersList_Active = new List<SPUser>();

            XDocument xDoc = XDocument.Parse(e.Result);
            var query = from g in xDoc.Descendants("Users")
            select new
            {
                ID = (Guid)g.Element("ID"),
                AccountName = (string)g.Element("AccountName"),
                FirstName = (string)g.Element("FirstName"),
                LastName = (string)g.Element("LastName"),
                FullName = (string)g.Element("FullName"),
                Department = (string)g.Element("Department"),
                Office = (string)g.Element("Office"),
                ImageUrl = (string)g.Element("ImageUrl"),
                SiteUrl = (string)g.Element("SiteUrl"),
                WorkPhone = (string)g.Element("WorkPhone"),
                Mail = (string)g.Element("Mail"),
                Staff = (string)g.Element("Staff"),
            };
            foreach (var n in query)
            {
                SPUser o = new SPUser();
                o.id = n.ID;
                o.ФИО = n.FullName;
                o.Имя = n.FirstName;
                o.Фамилия = n.LastName;
                o.Офис = n.Office;
                o.Отдел = n.Department;
                o.ImageUrl = n.ImageUrl;
                o.SiteUrl = n.SiteUrl;
                o.Тел = n.WorkPhone;
                o.EMail = n.Mail;
                o.Должность = n.Staff;
                o.AccountName = n.AccountName;
                App._SPUSersList.Add(o);
            }
            dataGrid1.ItemsSource = App._SPUSersList_Active;
            
            //____________________
            // Get AD Users List :
            Guid guid = Guid.NewGuid();
            DateTime dt = DateTime.Now;
            WebClient wbcl = new WebClient();
            wbcl.DownloadStringCompleted += new DownloadStringCompletedEventHandler(load_data3);
            Uri myUri = new Uri("http://sp.korablik.local:98/ws/Catalog/ADUsers.aspx?id=" + guid.ToString() + "&date=" + dt.ToShortDateString(), UriKind.Absolute);
            wbcl.DownloadStringAsync(myUri);
        }
        void load_data3(object sender, DownloadStringCompletedEventArgs e)
        {

            #region Members

            bool IsFind = false;
            List<SPUser> SPUserForDelList = new List<SPUser>();

            #endregion

            #region Prepare

            if (e.Error != null)
            {
                App._mainpage.hyperlink_all.IsEnabled = true;
                App._mainpage.hyperlink_office.IsEnabled = true;
                App._mainpage.hyperlink_search.IsEnabled = true;
                App._mainpage.hyperlink_shops.IsEnabled = true;
                App._IsLoading = false;
                MessageBox.Show("Error" + e.Error.Message);
                return;
            }

            App._ADUSersList.Clear();
            App._ADUSersList = null;
            App._ADUSersList = new List<ADUser>();

            #endregion

            #region XML Parse

            XDocument xDoc = XDocument.Parse(e.Result);
            var query = from g in xDoc.Descendants("Users")
                        select new
                        {
                            Login = (string)g.Element("Login"),
                            USERACCOUNTCONTROL = (string)g.Element("USERACCOUNTCONTROL"),
                            UserName = (string)g.Element("UserName"),
                            DisplayName = (string)g.Element("DisplayName"),
                            EMailAddress = (string)g.Element("EMailAddress"),
                            Office = (string)g.Element("Office"),
                            SN = (string)g.Element("SN"),
                            GIVENNAME = (string)g.Element("GIVENNAME"),
                            EXTENSIONATTRIBUTE3 = (string)g.Element("EXTENSIONATTRIBUTE3"),
                            PHYSICALDELIVERYOFFICENAME = (string)g.Element("PHYSICALDELIVERYOFFICENAME"),
                            EXTENSIONATTRIBUTE4 = (string)g.Element("EXTENSIONATTRIBUTE4"),
                            TELEPHONENUMBER = (string)g.Element("TELEPHONENUMBER"),
                            TITLE = (string)g.Element("TITLE"),
                            Department = (string)g.Element("Department"),
                            Company = (string)g.Element("Company"),
                            Manager = (string)g.Element("Manager"),
                        };
            foreach (var n in query)
            {
                ADUser o = new ADUser();
                o.Login = n.Login;
                o.USERACCOUNTCONTROL = n.USERACCOUNTCONTROL;
                o.UserName = n.UserName;
                o.DisplayName = n.DisplayName;
                o.EMailAddress = n.EMailAddress;
                o.Office = n.Office;
                o.SN = n.SN;
                o.GIVENNAME = n.GIVENNAME;
                o.EXTENSIONATTRIBUTE3 = n.EXTENSIONATTRIBUTE3;
                o.PHYSICALDELIVERYOFFICENAME = n.PHYSICALDELIVERYOFFICENAME;
                o.EXTENSIONATTRIBUTE4 = n.EXTENSIONATTRIBUTE4;
                o.TELEPHONENUMBER = n.TELEPHONENUMBER;
                o.TITLE = n.TITLE;
                o.Department = n.Department;
                o.Company = n.Company;
                o.Manager = n.Manager;
                App._ADUSersList.Add(o);
            }

            #endregion

            #region Remove Disabled users :

            foreach (SPUser spu in App._SPUSersList)
            {
                IsFind = false;
                foreach (ADUser adu in App._ADUSersList)
                {
                    string[] separator = { @"\" };
                    string strTmp = spu.AccountName;
                    string [] login1Arr = strTmp.Split(separator, StringSplitOptions.RemoveEmptyEntries);
                    string login1 = "";
                    if (login1Arr.Length > 0)
                        login1 = login1Arr[1];
                    string login2 = adu.Login;
                    if (login1 == login2)
                    {
                        IsFind = true;
                        break;
                    }
                }
                if (IsFind == false)
                {
                    SPUserForDelList.Add(spu);
                }
            }

            for (int i = App._SPUSersList.Count - 1; i >= 0; i--)
            {
                IsFind = false;
                foreach (SPUser u in SPUserForDelList)
                {
                    if (App._SPUSersList[i].AccountName == u.AccountName)
                    {
                        IsFind = true;
                        break;
                    }
                }
                if (IsFind == true)
                    App._SPUSersList.RemoveAt(i);
            }

            #endregion

            myTreeView.IsEnabled = true;
            App._mainpage.hyperlink_all.IsEnabled = true;
            App._mainpage.hyperlink_office.IsEnabled = true;
            App._mainpage.hyperlink_search.IsEnabled = true;
            App._mainpage.hyperlink_shops.IsEnabled = true;
            App._IsLoading = false;
        }
        private Exception InvalidateTree()
        {
            Exception ret = null;
            App.Topics = new ObjModel.ObservableCollection<Topic>();
            for (int i = 0; i < App._list.Count; i++)
            {
                if (App._list[i].IdParent == -1)
                {
                    AddNodeToRoot(App._list[i]);
                }
            }
            myTreeView.DataContext = App.Topics;
            return ret;
        }
        public void AddNodeToRoot(MyNode mynode)
        {
            int id = mynode.Id;
            int idParent = mynode.IdParent;
            string name = mynode.Name;
            Topic newtopic = new Topic(name, id, idParent);
            AddChildsNodes(ref newtopic);
            App.Topics.Add(newtopic);
        }
        public void AddChildsNodes(ref Topic node)
        {
            foreach (MyNode n in App._list)
            {
                int id = n.Id;
                int idParent = n.IdParent;
                string name = n.Name;
                if (n.IdParent == node.IdI)
                {
                    Topic newtopic = new Topic(name, id, idParent);
                    AddChildsNodes(ref newtopic);
                    node.ChildTopics.Add(newtopic);
                }
            }
        }
        private void AddData(string parID, string parIDParent, string parName)
        {
            int id = -1;
            int idparent = -1;
            if (!String.IsNullOrEmpty(parID))
                id = Convert.ToInt32(parID);
            if(id==-1)
                return;
            if (!String.IsNullOrEmpty(parIDParent))
                idparent = Convert.ToInt32(parIDParent);
            MyNode n = new MyNode();
            n.Id = id;
            n.IdParent = idparent;
            n.Name = parName;
            App._list.Add(n);
        }
        #endregion

    }      

}
